//
//  SAXXMLParser.m
//  UI19_XML数据解析作业
//
//  Created by dllo on 16/4/5.
//  Copyright © 2016年 付冬梅. All rights reserved.
//

#import "SAXXMLParser.h"
#import "CartoonModel.h"

@interface SAXXMLParser ()<NSXMLParserDelegate>


@property (nonatomic, strong) NSMutableArray *dataSouceArr;
@property (nonatomic, strong) NSMutableString *content;

@property (nonatomic, copy) NSString *currentElement;

@property (nonatomic, assign) NSInteger count;

@end
@implementation SAXXMLParser


+ (NSArray *)saxParserWithFileName:(NSString *)name fileType:(NSString *)type {
    SAXXMLParser *parser = [[SAXXMLParser alloc] init];
    parser.dataSouceArr = [NSMutableArray array];
    
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:name ofType:type]]];
    xmlParser.delegate = parser;
    [xmlParser parse];
    return parser.dataSouceArr;
    
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict {
    
    if ([elementName isEqualToString:@"AlbumInfo"]) {
        CartoonModel *model = [[CartoonModel alloc] init];
        [self.dataSouceArr addObject:model];
    }
    
    self.currentElement = [NSString stringWithString:elementName];
    self.content = [NSMutableString string];
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    NSLog(@"%@", self.content);
//    if (_count == 0) {
//        self.content = string.mutableCopy;
//    } else {
//         [self.content stringByAppendingString:string];
//        
//    }
//    _count++;
//    NSLog(@"%ld", _count);
//    [self.content appendString:string];
    if ([self.currentElement isEqualToString:@"desc"]) {
       [self.content appendString:string];
    } else {
        self.content = string.mutableCopy;
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    
    CartoonModel *model = [self.dataSouceArr lastObject];
    if ([elementName isEqualToString:@"name"]) {
        model.name = self.content;
    }
    if ([elementName isEqualToString:@"middlePicurl"]) {
        model.picUrl = self.content;
    }
    if ([elementName isEqualToString:@"desc"]) {
        model.desc = self.content;
    }
//    if ([elementName isEqualToString:self.currentElement]) {
//        self.content = nil;
//    }
//    _count = 0;
}

@end
